package com.zyl.blog.common.utils.Extreme;

import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;

import java.time.Duration;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog
 * @Package: com.zyl.common.utils.Extreme
 * @ClassName: TriggerFormatter
 * @Description:
 * @Author FinalFantasy
 * @Date 2025/3/26-21:38
 */
public class TriggerFormatter {

    public static String format(Trigger trigger) {
        if (trigger instanceof CronTrigger) {
            return handleCronTrigger((CronTrigger) trigger);
        } else if (trigger instanceof PeriodicTrigger) {
            return handlePeriodicTrigger((PeriodicTrigger) trigger);
        }
        return trigger.toString();
    }

    private static String handleCronTrigger(CronTrigger trigger) {
        return "Cron任务: " + trigger.getExpression();
    }

    private static String handlePeriodicTrigger(PeriodicTrigger trigger) {
        // 新版 API 获取时间间隔
        Duration duration = trigger.getPeriodDuration();
        String cronExpression = generateCronExpression(duration);
        String taskType = trigger.isFixedRate() ? "固定频率任务" : "固定延迟任务";
        return String.format("%s: %s", taskType, cronExpression);
    }

    private static String generateCronExpression(Duration duration) {
        long seconds = duration.getSeconds();

        if (seconds <= 0) {
            return "立即执行（间隔无效）";
        }

        if (seconds < 60) {
            return String.format("*/%d * * * * ?", seconds);
        } else if (seconds < 3600) {
            long minutes = seconds / 60;
            return seconds % 60 == 0 ?
                    String.format("0 */%d * * * ?", minutes) :
                    String.format("0 %d/%d * * * ?", seconds/60, minutes);
        } else if (seconds < 86400) {
            long hours = seconds / 3600;
            return String.format("0 0 */%d * * ?", hours);
        } else {
            long days = seconds / 86400;
            return String.format("0 0 0 */%d * ?", days);
        }
    }
}